<template>
  <div id="plan-list">
    <div class="search-box">
      <el-form>
        <el-form-item label="店铺名称：">
            <el-select v-model="searchForm.shopId" placeholder="请选择店铺" size="small" filterable :filter-method="dataFilter" clearable>
              <el-option v-for="(item, index) in shopNameList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计划ID ：">
        	<el-input placeholder="请输入计划ID" size="small" v-model="searchForm.planCode" clearable></el-input>
        </el-form-item>
        <el-form-item label="商品ID：">
        	<el-input placeholder="请输入商品ID" size="small" v-model="searchForm.productId" clearable></el-input>
        </el-form-item>
        <el-form-item label="计划名称 ：">
        	<el-input placeholder="请输入计划名称" size="small" v-model="searchForm.planName" clearable></el-input>
        </el-form-item>
        <el-form-item label="起止时间 ：">
        	<div class="block">
        		<el-date-picker size="small" v-model="searchTime" type="datetimerange" range-separator="至"
        		:picker-options="pickerOptions" start-placeholder="开始日期" end-placeholder="结束日期" @change="changeTime"></el-date-picker>
        	</div>
        </el-form-item>
        <el-form-item>
          <el-button class="search-btn" icon="el-icon-ali-search" @click="searchData()">查&nbsp;询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-box">
      <div class="tabs-nav">
        <div class="tab" :class="searchForm.status == item.type ? 'active':''" v-for="(item,index) in tabsList" :key="index" @click="changeTab(item.type)">{{item.name}}</div>
      </div>
      <div class="plan-list">
        <div class="plan-card"  v-for="(item,index) in tableData" :key="index">
          <div class="plan-card-header">
              <i class="platform-img" :class="platformImgObject[item.shop_type]"></i>
              <span class="shop-name">{{getShopType(item.shop_type)}}-{{item.shop_name}}</span>
              <span class="header-right">
                <span><i class="header-right-icon el-icon-ali-time"></i>创建时间：{{item.create_time == null ? '--' : item.create_time}}</span>
                <span class="plan-status"><i class="header-right-icon el-icon-ali-status"></i>计划状态：<span class="status-text">{{getTaskStatus(item.status)}}</span></span>
              </span>

          </div>
          <div class="plan-card-body">
            <img class="goods-img" :src="item.goods_info.goods_img" alt="">
            <div class="plan-info">
              <div>计划名称：{{item.plan_name}}</div>
              <div>计划ID：{{item.plan_code}}</div>
              <div>商品ID：{{item.goods_info.product_id}}</div>
              <div class="time-box">
                <span>
                  <i class="time-icon el-icon-ali-time"></i>
                  <span class="time">开始时间：{{item.start_time == 0 ? '--' : getFormatTime(parseInt(item.start_time * 1000))}} -- 结束时间：{{item.end_time == 0 ? '--' : getFormatTime(parseInt(item.end_time * 1000))}}</span>
                </span>
                <span>
                  <i class="time-icon el-icon-ali-time"></i>
                  <span class="time">终止时间：{{item.over_time == 0 ? '--' : getFormatTime(parseInt(item.over_time * 1000))}}</span>
                </span>
              </div>
            </div>
          </div>
          <div class="task-type-status">
            <span class="type-box"><span style="color: red;">待人工审核：</span>{{item.wait_check_men_num}}</span>
            <span class="type-box"><span>总数：</span>{{item.all_num}}</span>
            <span class="type-box"><span>等待执行：</span>{{item.wait_num}}</span>
            <span class="type-box"><span>已派单未接单：</span>{{item.wait_get_num}}</span>
            <span class="type-box"><span>正在操作：</span>{{item.real_num}}</span>
            <span class="type-box"><span>待审核：</span>{{item.wait_check_num}}</span>
            <span class="type-box"><span>执行成功：</span>{{item.success_num}}</span>
            <span class="type-box"><span>执行失败：</span>{{item.fail_num}}</span>
          </div>
          <div class="plan-card-footer">
            <el-button icon="el-icon-ali-look" class="dark-color-btn"  @click="toPlanDetail(item.id)" v-if="item.status != 5">查看详情</el-button>
            <el-button icon="el-icon-ali-copy" class="light-color-btn" @click="copyPlanTask(item.id, item)" v-if="item.status != 5">复制计划</el-button>
            <el-button icon="el-icon-ali-pay" class="dark-color-btn"  @click="goToPay(item.id, item)" v-if="item.status == 5">前往支付</el-button>
            <el-button icon="el-icon-ali-stop" class="light-color-btn" @click="stopPlan(item.id)" v-if="item.status == 5">终止计划</el-button>
          </div>
        </div>
        <div class="no-data-img" v-if="tableData.length == 0">
          <img src="../../assets/image/no-data.png" alt="">
          <div class="tips">暂无数据</div>
        </div>
      </div>
      <div class="block" style="margin: 20px 0px; text-align: right;">
      	<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="searchForm.page"
      	 :page-sizes="[10, 20, 30, 40,50]" :page-size="searchForm.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pageTotal"></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
  import {
   apiGetMerchantShopList,
   apiSalePlanList,
   apiFlowPlanList,
   apiStopSalesPlan,
   apiStopFlowPlan
  } from '../../request/api.js'
  import { mapGetters,mapActions} from 'vuex';
  export default{
    data(){
      return {
        planListType: 'sales',
        shopNameList: [],
        shopNameOptions: [],
        searchTime: [],
        tableData:[],
        searchForm: {
          token: '',
          page: 1,
          pageSize: 10,
        	shopId: '',
        	productId: '',
        	planCode: '',
        	planName: '',
          startTime: '',
          endTime: '',
          status: '',
          shopType: window.localStorage.getItem('curSelectShowType')
        },
        tabsList:[{
          type: '',
          name: '全部计划'
        },{
          type: 5,
          name: '创建中'
        },{
          type: 1,
          name: '等待执行'
        },{
          type: 2,
          name: '正在执行'
        },{
          type: 3,
          name: '执行完成'
        },{
          type: 4,
          name: '人工终止'
        }],
        platformNameObject:{
          1: '淘宝',
          2: '天猫',
          3: '京东',
		  4: '1688',
          13: '唯品会',
          15: '拼多多'
        },
        platformImgObject:{
          1: 'el-icon-ali-tb',
          2: 'el-icon-ali-tm',
          3: 'el-icon-ali-jd',
          4: 'el-icon-ali-1688_icon',
          13: 'el-icon-ali-wph',
          15: 'el-icon-ali-pdd'
        },
        pickerOptions: {
          disabledDate(time) {
             let merchantTime = window.localStorage.getItem('merchantTime')
             let curDate = (new Date()).getTime();
             let three = merchantTime * 24 * 3600 * 1000;
             let threeMonths = curDate - three;
             return time.getTime() < threeMonths;
          },
        },
        pageTotal: 0,
        tagsList: {},
        curShopType: window.localStorage.getItem('curSelectShowType'),
         userToken: window.localStorage.getItem('token')
      }
    },
    created() {
      this.searchForm.token = this.userToken
      this.getShopList()
      this.getTableData()
    },
    watch: {
      //监听路由跳转
      '$route': {
        handler: function (to, from) {
          if (to.path == '/plan/salesPlanList') {
            this.planListType = 'sales'
          } else{
            this.planListType = 'flow'
          }
        },
        immediate: true,
      },
      curShopType:function(val){
        this.searchForm.shopType = val
        console.log(this.merchantTime)
        this.getTableData()
      }
    },
    methods:{
      searchData(){
        this.searchForm.page = 1
        this.searchForm.pageSize = 10
        this.getTableData()
      },
      getTableData(){
        if(this.planListType == 'sales'){
          this.$isClick(true);
          apiSalePlanList(this.searchForm).then(res =>{
            this.$isClick(false);
             if (res.code == 1){
               this.pageTotal = res.msg.allNum
               this.tableData = res.msg.res
             } else {
               this.$message.error(res.msg);
             }
          }).catch(res => {
            this.$isClick(false);
              this.$message.error(res.msg)
          })
        } else {
          this.$isClick(true);
          apiFlowPlanList(this.searchForm).then(res =>{
            this.$isClick(false);
             if (res.code == 1){
               this.pageTotal = res.msg.allNum
               this.tableData = res.msg.res

             } else {
               this.$message.error(res.msg);
             }
          }).catch(res => {
            this.$isClick(false);
              this.$message.error(res.msg)
          })
        }
      },
      //获取店铺名称
      getShopList() {
        this.$isClick(true);
        apiGetMerchantShopList({
          token: this.userToken
        }).then(res =>{
          this.$isClick(false);
           if (res.code == 1){
             for (var i in res.msg.merchant_shop_list) {
               this.shopNameList.push({
                 name: res.msg.merchant_shop_list[i].name,
                 id: res.msg.merchant_shop_list[i].id
               })
             }
             this.shopNameOptions = this.shopNameList
           } else {
             this.$message.error(res.msg);
           }
        }).catch(res => {
          this.$isClick(false);
            this.$message.error(res.msg)
        })
      },
      dataFilter(val) {
        this.searchForm.shopId = val;
        if (val) { //val存在
          this.shopNameList = this.shopNameOptions.filter((item) => {
            if (!!~item.name.indexOf(val) || !!~item.name.toUpperCase().indexOf(val.toUpperCase())) {
              return true
            }
          })
        } else { //val为空时，还原数组
          this.shopNameList = this.shopNameOptions;
        }
      },
      changeTime(val){
       this.searchForm.startTime =  this.changeTimestamp(val[0])
       this.searchForm.endTime =  this.changeTimestamp(val[1])
      },
      changeTimestamp(time){
        var d = new Date(time);
        var s = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
        return new Date(s).getTime() /1000;
      },
      getFormatTime (date){
         date = new Date(date)
         var Y = date.getFullYear() + '-';
         var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
         var D = (date.getDate() < 10 ? '0' +  date.getDate() : date.getDate()) + ' ';
         var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
         var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
         var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
         return Y + M + D + h + m + s;
      },
      getShopType(type){
        return this.platformNameObject[type]
      },
      changeTab(val){
        this.searchForm.status = val
        this.getTableData()
      },
      getTaskStatus (val){
        var text = ''
        switch (val){
          case 1:
          text = '等待执行'
            break;
          case 2:
          text = '正在执行'
            break;
          case 3:
          text = '执行完成'
            break;
          case 4:
          text = '人工终止'
            break;
          case 5:
          text = '创建中'
            break;
          default:
          text = '全部计划'
            break;
        }
        return text
      },
      toPlanDetail(id){
        if(this.planListType == 'sales'){
          this.$router.push("./salesPlanDetail?id=" + id);
        } else {
           this.$router.push("./flowPlanDetail?id=" + id);
        }

      },
      copyPlanTask(id, item) {
        if(this.planListType == 'sales'){
          if ((item.shop_type == 1 || item.shop_type == 2)
            && item.is_onedragn == 1) {// is_onedragn 1代表1拖n 2代表普通
            // 新建淘宝天猫一拖N计划
            this.$router.push(`./createDragPlan?id=${id}&type=copy`);
          } else {
            // 新建计划
            this.$router.push(`./createSalsePlan?id=${id}&type=copy`);
          }
        } else {
           this.$router.push(`./createFlowPlan??id=${id}&type=copy`);
        }

      },
      goToPay(id, item){
        if(this.planListType == 'sales'){
          if ((item.shop_type == 1 || item.shop_type == 2)
            && item.is_onedragn == 1) {// is_onedragn 1代表1拖n 2代表普通
            // 前往支付 淘宝天猫一托N计划
            this.$router.push("./createDragPlan?id=" + id + "&type=pay");
          } else {
            this.$router.push("./createSalsePlan?id=" + id + "&type=pay");
          }
        } else {
          this.$router.push("./createFlowPlan?id=" + id + "&type=pay");
        }
      },
      stopPlan(id){
        if(this.planListType == 'sales'){
          this.$isClick(true);
          apiStopSalesPlan({
            token: this.userToken,
            id:id
          }).then(res =>{
            this.$isClick(false);
             if (res.code == 1){
               this.$message.success('终止成功');
               this.getTableData()
             } else {
               this.$message.error(res.msg);
             }
          }).catch(res => {
            this.$isClick(false);
              this.$message.error(res.msg)
          })
        } else {
          this.$isClick(true);
          apiStopFlowPlan({
            token: this.userToken,
            id:id
          }).then(res =>{
            this.$isClick(false);
             if (res.code == 1){
               this.$message.success('终止成功');
               this.getTableData()
             } else {
               this.$message.error(res.msg);
             }
          }).catch(res => {
            this.$isClick(false);
              this.$message.error(res.msg)
          })
        }
      },
      handleSizeChange(val) {
      	this.searchForm.pageSize = val;
      	this.getTableData()
      },
      handleCurrentChange(val) {
      	this.searchForm.page = val;
      	this.getTableData()
      },
    }
  }
</script>

<style lang="less">
  #plan-list {
    .table-box {
      .tabs-nav {
        border-radius: 5px;
        border: 1px solid #e0e0e0;
        display: inline-block;
        .tab {
          display: inline-block;
          font-size: 13px;
          color: @fontSubtitleColor;
          padding: 5px 12px;
          cursor: pointer;
          &:nth-child(1){
           &.active {
            border-top-left-radius: 5px;
            border-bottom-left-radius: 5px;
           }
          }
          &:nth-child(2),&:nth-child(3),&:nth-child(4),&:nth-child(5){
            border-left: 1px solid #a5a5a5;
          }
          &:nth-child(6){
            border-left: 1px solid #a5a5a5;
           &.active {
            border-top-right-radius: 5px;
            border-bottom-right-radius: 5px;
           }
          }
          &.active {
            color: #FFFFFF;
            background: @themeColor;
          }
        }
      }
    }
    .plan-list {
      margin-top: 10px;
      .plan-card {
        border: 1px solid #e0e0e0;
        border-radius: 5px;
        margin-bottom: 16px;
        .plan-card-header {
          background: #ecf5ff;
          padding: 10px;
          display: flex;
          align-items: center;
          position: relative;
          .platform-img {
            &.el-icon-ali-tb {
              color: rgb(253,77,15);
            }
            &.el-icon-ali-jd{
              color: rgb(241,48,24);
            }
            &.el-icon-ali-pdd {
              color: rgb(240,16,15);
            }
            &.el-icon-ali-tm {
              color: rgb(253,17,39);
            }
            &.el-icon-ali-wph {
              color: rgb(219,16,113);
            }
            &.el-icon-ali-1688_icon {
              color: rgb(255, 103, 4);
            }
            font-size: 25px;
          }
          .shop-name {
            font-size: 14px;
            color: @fontTitleColor;
            margin-left: 10px;
          }
          .header-right {
            position: absolute;
            right: 16px;
            top: 13px;
            font-size: 14px;
            color: @fontTitleColor;
            .header-right-icon {
              font-size: 14px;
              margin-right: 5px;
            }
            .plan-status {
              margin-left: 20px;
              .status-text {
                color: red;
                font-weight: bold;
              }
            }
          }

        }
        .plan-card-body {
          display: flex;
          align-items: center;
          padding: 16px;
          .goods-img {
            width: 100px;
            height: 100px;
          }
          .plan-info {
            font-size: 14px;
            color: @fontSubtitleColor;
            margin-left: 16px;
            div {
              line-height: 26px;
            }
            .time-box {
              .time-icon {
                font-size: 14px;
                margin-right: 5px;
              }
              .time {
                margin-right: 20px;
              }
            }
          }
        }
        .task-type-status {
          font-size: 14px;
          padding-left: 16px;
          padding-bottom: 16px;
          color: @fontSubtitleColor;
          .type-box {
            margin-right: 30px;
            span{
              color: @themeColor;
            }
          }
        }
        .plan-card-footer {
          text-align: right;
          border-top: 1px solid #e0e0e0;
          padding: 10px 16px;
          .dark-color-btn {
            background: @themeColor;
            color: #FFFFFF;
            font-size: 14px;
            padding: 8px 20px;
          }
          .light-color-btn {
            background: #2d67a9;
            color: #FFFFFF;
            font-size: 14px;
            padding: 8px 20px;
          }
        }
      }
    }
    .no-data-img {
      text-align: center;
      margin-top: 80px;
      .tips{
        font-size: 14px;
        margin-top: 10px;
      }
    }
  }
</style>
